package com.xyxy.platform.modules.service.trade.impl;

import com.google.common.collect.Lists;
import com.xyxy.platform.modules.core.cache.memcached.SpyMemcachedClient;
import com.xyxy.platform.modules.core.utils.Collections3;
import com.xyxy.platform.modules.service.trade.CategoryService;
import com.xyxy.platform.modules.service.trade.CategoryTreeService;
import com.xyxy.platform.modules.service.trade.vo.CategoryTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * Created by czd on 16/1/22.
 */
@Service
public class CategoryTreeServiceImpl implements CategoryTreeService {


    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SpyMemcachedClient cacheClient;

    private final String cacheKey = "CategoryTreeServiceImpl_memcacheKey";

    @PostConstruct
    private void init() {
        this.generateCategoryTree();
    }

    /**
     * 构建分类树信息
     *
     * @return
     */
    private List<CategoryTree> generateCategoryTree() {
        List<CategoryTree> result = Lists.newArrayList();

        List<CategoryTree> categoryList = categoryService.findAllWithTree();

        Map<Long, CategoryTree> categoryMap = Collections3.extractToMap(categoryList, "id");

        for (CategoryTree tree : categoryList) {
            Long pid = tree.getParentId();
            if(tree.getIsDelete()==1){
                continue;
            }
            if (pid != 0) {
                CategoryTree parent = categoryMap.get(pid);
                parent.getChildList().add(tree);
            } else {
                result.add(tree);
            }
        }
        //缓存 24 小时
        cacheClient.set(cacheKey, 60 * 60 * 24, result);
        return result;
    }

    @Override
    public List<CategoryTree> getCategoryTree() {
        List<CategoryTree> categoryTreeList = cacheClient.get(this.cacheKey);
        if (Collections3.isEmpty(categoryTreeList)) {
            categoryTreeList = this.generateCategoryTree();
        }
        return Collections3.isEmpty(categoryTreeList) ? Lists.<CategoryTree>newArrayList() : categoryTreeList;
    }

    @Override
    public void clearCache() {
        cacheClient.delete(this.cacheKey);
    }


}
